chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {

    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");

    operationFactory(request.greeting, request.data);
    
    sendResponse({farewell: "goodbye"});
  });

currentTab = undefined;
currentTabId = undefined;
allTabs = [];
allTabsIds = [];
lastClosedTabUrl = undefined;

function operationFactory(operationCode, data) {
    if (operationCode == "Z")
      reopenLast();
    else if(operationCode == "P"){
      //getCurrentTab();
      moveToPrev();
    }  
    else if(operationCode == "O"){
      // alert("else if");
      moveToNext();
    }
    else if (operationCode == "C") {
      reloadCurrent();
    }
    else if (operationCode == "U") {
      reloadAll();
    }
    else if (operationCode == "S") {
      removeCurrent();
    }
    else if (operationCode == "M") {
      removeAll();
    }
    else if(operationCode == "url"){
      createTab(data,false);
    }



    // else{
    //   createTab(operationCode,false);
    // }
}

function createTabData(url, selected) {
  return {
    // 'index': parseInt(document.getElementById('index_' + id).value),
    // 'windowId': parseInt(document.getElementById('windowId_' + id).value),
    // 'index': parseInt(document.getElementById('index_' + id).value),
    'url': url,
    'selected': selected
  }
}

function createTab(url, ifSelected) {
  console.log("createTab");
  var args = createTabData(url, ifSelected);
  console.log(args);
  try {
    chrome.tabs.create(args);
  } catch (e) {
    alert(e);
  }
}

function getCurrentTab() {
  try{
    //  chrome.tabs.query({active: true},function(tab){
    //       currentTab = tab;
    // });
    chrome.tabs.getSelected(function(tab){
      currentTab = tab;
    });
  } catch(e) {
    alert(e);
  }
}

function getCurrentTabId() {
  getCurrentTab();
  currentTabId = currentTab.id;
}

function getAllTabs() { 
  try{
    chrome.tabs.getAllInWindow(function(tabs){ 
      allTabs = tabs;
      // alert(allTabs.length);
    });
  } catch(e) {
      alert(e);
  }
}

function getAllTabsIds() {
  getAllTabs();
  window.allTabsIds = [];
  for (var i = 0; i < allTabs.length; i++) {
    window.allTabsIds.push(allTabs[i].id);
  };
}

function removeTab(tabIds) {
  try {
    if(tabIds.length > 1)
      alert("Shut up, I am gonna close them all");
    else
      alert("NO WAY! I am closing! Leave me alone!")
    chrome.tabs.remove(tabIds);
  } catch (e) {
    alert(e);
  }
}
//operation code: S
function removeCurrent() {
  getCurrentTabId();
  removeTab(currentTabId);
}
//operation code: M
function removeAll() {
  getAllTabsIds();
  // alert(allTabsIds.length);
  removeTab(allTabsIds);
}

function reloadTab(tabId) {
  try {
    chrome.tabs.reload(tabId)
  } catch (e) {
    alert(e);
  }
}
//operation code: C
function reloadCurrent() {
  getCurrentTabId();
  reloadTab(currentTabId);
}
//operation code: U
function reloadAll() {
  // alert("reloadall");
  getAllTabsIds();
  for (var i = 0; i < allTabsIds.length; i++) {
    //alert(i);
    reloadTab(allTabsIds[i]);
  };
}
//operation code: O
function moveToNext() {
  changeSelected(1);
}
//operation code: P
function moveToPrev() {
  changeSelected(-1);
}

function changeSelected(offset) {
  getCurrentTabId();
  getAllTabsIds();
  index = (currentTab.index + offset) % allTabsIds.length;
  //alert(index);
  id = findIdByIndex(index);
  //alert(id);
  try{
    chrome.tabs.update(currentTab.id,{active: false});
    chrome.tabs.update(id,{active: true});
  } catch(e) {
    alert(e);
  }
}

function findIdByIndex(index) {
  getAllTabsIds();
  for (var i = 0; i < allTabs.length; i++) {
    if (allTabs[i].index == index) {
      return allTabs[i].id;
    };
  };
}
//operation code: Z
function reopenLast() {
  // alert(lastClosedTabUrl);
  createTab(lastClosedTabUrl,true);
}

chrome.tabs.onCreated.addListener(function(tab) {
  getCurrentTabId();
  getAllTabsIds();
});

chrome.tabs.onUpdated.addListener(function(tab) {
  getCurrentTabId();
  getAllTabsIds();
});

chrome.tabs.onRemoved.addListener(function(tabId, removeInfo) {
  // alert(allTabs.length);
  // alert(tabId);
  for (var i = 0; i < allTabs.length; i++) {
    if (allTabs[i].id == tabId) {
      //alert("here");
      lastClosedTabUrl = allTabs[i].url;
    };
  };
  getAllTabsIds();
  getCurrentTabId();
});